package com.edooteach.tencent.web.controller.message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.wechat.entity.token.Token;
import com.edooteach.tencent.accessor.CorpTokenAssessor;
import com.edooteach.tencent.entity.corpmessage.CorpMessageRequest;
import com.edooteach.tencent.handle.CorpMessageHandler;

/**
 * 
 * @author mohanlan
 *
 */
@RestController
@RequestMapping("/corp/messages")
public class CorpMessageController {
  
    private static final Logger logger = LoggerFactory.getLogger(CorpMessageController.class);
    
    @Autowired
    private CorpTokenAssessor corpTokenAssessor;
    
    @Autowired
    private CorpMessageHandler corpMessageHandler;
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult send(@RequestBody CorpMessageRequest corpMessageRequest) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
          
          // 1. validate corpMessageRequest
          if(!corpMessageRequest.isValid()) {
            throw BusinessException.newInstance("400", "参数异常");
          }
          
          Token token = corpTokenAssessor.requestAccessToken(); 
          
          httpResult = corpMessageHandler.send(token.getAccessToken(), corpMessageRequest);
          
        } catch (Exception e) {
          
          logger.error("do send corp message occurs error: ", e);
          httpResult.fail("500").message("发送信息异常");
        }
        
        return httpResult;
    }
    
}
